<?php


namespace app\api\controller;


use app\common\lib\Export;
use app\common\lib\Request;
use app\api\model\Dynamic_dynamic;
use app\api\model\Dynamic_file;
use think\Container;
use think\Exception;
use app\api\validate\Dynamic_dynamic as validate;
use app\api\model\Dynamic_operation;
use app\api\model\Dynamic_comment;
use app\api\model\Message_prompt;
use app\api\task\Prompt;
use app\api\model\User;
use app\api\model\User_operation;

class Dynamic extends Base
{

    private $cmd_data = [
        // 发布动态
        "100"=>"public_dynamic",
        // 删除动态
        "101"=>"del_dynamic",
        // 点赞动态
        '102'=>'praise_dynamic',
        // 评论动态
        '103'=>'public_comment',
        // 点赞评论
        '104'=>'praise_comment',
        // 动态详情
        '105'=>'dynamic_detail',
        // 获取我的动态列表
        '106'=>'get_my_dynamic',
        // 获取别人的动态列表
        '107'=>'get_dynamic',
    ];
    /** 入口 */
    public function index(){
        try{
            // 检验登录情况
            parent::check_user_info();

            $cmd = Request::get('cmd');
            if(!array_key_exists($cmd,$this->cmd_data)) throw new Exception("参数错误");
            $method = $this->cmd_data[$cmd];

            $this->$method();
        }catch (Exception $e){
            Export::exp_err($e->getMessage());
        }

        return '';
    }

    /** 发布动态 */
    private function public_dynamic(){
        $data = Request::post(["content"]);


        $data['permission'] = isset($data['permission']) ? $data['permission']:0;
        $data['see_user_list'] = isset($data['see_user_list']) && $data['permission']==2 ? $data['see_user_list']:[];
        $data['no_see_user_list'] = isset($data['no_see_user_list']) && $data['permission']==3 ? $data['no_see_user_list']:[];
        $data['is_set_top'] = isset($data['is_set_top']) ? 1:0;


        // 参数验证
        $validate = new validate();

        if (!$validate->check($data)) {
            throw new Exception($validate->getError());
        }

        // 保存动态
        $dynamic = Dynamic_dynamic::create([
            "user_id"=>$this->user_id,
            "content"=>$data['content'],
            "is_set_top"=>$data['is_set_top'],
            "see_user_list"=>json_encode($data['see_user_list'],true),
            "no_see_user_list"=>json_encode($data['no_see_user_list'],true),
        ]);

        // 保存动态添加的图片
        if(array_key_exists('images',$data) && $data['images']){
            $images = is_array($data['images'])?$data['images']:[$data['images']];
            $dynamic_file = new Dynamic_file();
            $list = [];
            $base = [
               "dynamic_id"=>$dynamic['id'],
            ];
            foreach ($images as $image){
                $item = [
                    'file_url'=>$image,
                ];
                $list[] = array_merge($base,$item);
            }
            $dynamic_file->saveAll($list);
        }

        Export::exp_ok();
    }

    /** 101 删除动态 */
    private function del_dynamic(){
        $data = Request::post(["id"]);

        $dynamic = Dynamic_dynamic::get($data['id']);
        if(!$dynamic) throw new Exception("该动态不存在");
        if($dynamic->user_id !=$this->user_id) throw new Exception("无权限删除");

        $dynamic->delete();

        Export::exp_ok();
    }
    /** 102 点赞 */
    private function praise_dynamic(){
        $data = Request::post(["id",'state']);

        $dynamic = Dynamic_dynamic::get($data['id']);
        if(!$dynamic) throw new Exception("该动态不存在");

        $where = [
            "object_id"=>$dynamic->id,
            "user_id"=>$this->user_id,
            "type"=>0,
        ];
        $operation = Dynamic_operation::where($where)->find();

        if($data['state']){
            if(!$operation){
                $operation = Dynamic_operation::create([
                    "object_id"=>$dynamic->id,
                    "user_id"=>$this->user_id,
                    "type"=>0,
                ]);

                Dynamic_dynamic::where('id', $dynamic->id)
                    ->setInc('praise_num', 1);

                //保存消息提示
                $this->save_prompt($dynamic->user_id,$this->user_id,$dynamic->id,$operation->id,Message_prompt::$praise_dynamic_type);
            }
        }else{
            if($operation){
                $operation->delete();

                Dynamic_dynamic::where('id', $dynamic->id)
                    ->setDec('praise_num', 1);
                //保存消息提示
                $this->save_prompt($dynamic->user_id,$this->user_id,$dynamic->id,$operation->id,Message_prompt::$praise_dynamic_type,0);
            }
        }

        Export::exp_ok();

    }


    /** 103评论动态 */
    private function public_comment(){
        $data = Request::post(["id",'content','pic']);
        // 动态判断
        $dynamic = Dynamic_dynamic::get($data['id']);
        if(!$dynamic) throw new Exception("该动态不存在");

        $data['p_id'] = isset($data['p_id'])?$data['p_id']:0;
        if($data['p_id']){
            $comment = Dynamic_comment::get($data['p_id']);
            if(!$comment){
                throw new Exception("该评论不存在");
            }
        }

        $res = Dynamic_comment::create([
            "dynamic_id"=>$dynamic->id,
            "user_id"=>$this->user_id,
            "p_id"=>$data['p_id'],
            "pic"=>$data['pic'],
            "content"=>$data['content'],
        ]);

        if(!$res) throw new Exception("系统繁忙");

        //保存消息提示
        $type = $data['id']?Message_prompt::$comment_comment_type:Message_prompt::$comment_dynamic_type;
        $this->save_prompt($dynamic->user_id,$this->user_id,$dynamic->id,$res->id,$type);


        Export::exp_ok();
    }

    /** 104点赞评论 */
    private function praise_comment(){
        $data = Request::post(["id",'state']);

        $comment = Dynamic_comment::get($data['id']);
        if(!$comment) throw new Exception("该评论不存在");

        $where = [
            "object_id"=>$comment->id,
            "user_id"=>$this->user_id,
            "type"=>2,
        ];
        $operation = Dynamic_operation::where($where)->find();
        if($data['state']){
            // 点赞
            if(!$operation){
                $operation = Dynamic_operation::create([
                    "object_id"=>$comment->id,
                    "user_id"=>$this->user_id,
                    "type"=>2,
                ]);
                Dynamic_comment::where('id', $comment->id)
                    ->setInc('praise_num', 1);
                //保存消息提示
                $this->save_prompt($comment->user_id,$this->user_id,$comment->id,$operation->id,Message_prompt::$praise_comment_type);
            }
        }else{
            // 取消点赞
            if($operation){
                $operation->delete();

                Dynamic_comment::where('id', $comment->id)
                    ->setDec('praise_num', 1);

                //保存消息提示
                $this->save_prompt($comment->user_id,$this->user_id,$comment->id,$operation->id,Message_prompt::$praise_comment_type,0);
            }
        }

        Export::exp_ok();
    }
    /** 105 获取动态详情 */
    private function dynamic_detail(){
        $data = Request::post(["id","page","page_size"]);
        $dynamic = Dynamic_dynamic::get($data['id']);
        if(!$dynamic) throw new Exception("该动态不存在");

        $comment_where = [
            ['dynamic_id','=',$dynamic->id],
            ['p_id','=',0],
        ];
        $comment = Dynamic_comment::where($comment_where)
            ->order(["create_time"=>"asc"])
            ->paginate($data['page_size'])->toArray();
        if($comment){
            foreach ($comment['data'] as &$item){
                $user = User::where(['id'=>$item['user_id']])->field('name,pic_url')->find();
                $item['user'] = $user;
                $item['sub_comment_count'] = Dynamic_comment::where(['p_id'=>$item['id']])->count();
            }
        }
        $info = [
            "dynamic"=>$dynamic,
            "comment"=>$comment,

        ];
        Export::exp_ok($info);
    }
    /** 106获取我的动态列表 */
    public function get_my_dynamic(){

        $data = Request::post(["page","page_size"]);

        $dynamic = Dynamic_dynamic::where([
                "user_id"=>$this->user_id,
            ])->order(['is_set_top'=>'desc',"create_time"=>"desc"])
            ->paginate($data['page_size'])->toArray();
        if($dynamic){
            foreach ($dynamic as &$item){
                $item['file'] = Dynamic_file::where([
                    "dynamic_id"=>$item['id']
                ])->field("file_url")->select();
            }
        }
        $info = [
            "data"=>$dynamic
        ];

        Export::exp_ok($info);
    }
    /** 获取动态 */
    public function get_dynamic(){
        $data = Request::post(["page","page_size"]);


        if(isset($data['user_id'])){
            // 个人动态
            $where = ['user_id'=>$data['user_id']];
        }else{
            // 好友动态
            $user_id = $this->user_id;
            $where = [
                [
                    'user_id',
                    ['IN', function ($query) use ($user_id) {
                        $query->table('user_operation')->where([
                            ['user_id','=', $user_id]
                        ])->field('object_user_id');
                    }],
                    ["=",$this->user_id],
                    'or'
                ]
            ];
        }

        $permission1 = [
            ["permission","=",0]
        ];
        $permission2 = [
            ["see_user_list","like","%\"{$this->user_id}\"%"],
            ["permission","=",2]
        ];
        $permission3 = [
            ["no_see_user_list","NOT LIKE","%\"{$this->user_id}\"%"],
            ["permission","=",3]
        ];
        $dynamic = Dynamic_dynamic::where($where)
            ->where(function($query) use($permission1, $permission2,$permission3) {
                $query->whereOr([
                    $permission1,$permission2,$permission3
                ]);
            })->order(['is_set_top'=>'desc',"create_time"=>"desc"])->paginate($data['page_size'])->toArray();

        Export::exp_ok($dynamic);
    }



    /** 内部实现方法 */


    /**
     * 异步插入消息提示
     * @param int type 0，关注；1，动态点赞；2，动态评论；3，评论点赞；4，评论评论
     */
    private function save_prompt($user_id,$operate_user_id,$object_id,$operate_id,$type,$increment=1){

        $task_data = [
            "user_id"=>$user_id,
            "operate_user_id"=>$operate_user_id,
            "operate_id"=>$operate_id,
            "object_id"=>$object_id,
            "type"=>$type,
            "increment"=>$increment,
        ];
        $task_Dynamic = new Prompt(100,$task_data);
        Container::get('swoole')->task($task_Dynamic);
    }
}